package app.maker.controleur;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.maker.entity.User;
import app.maker.error.UserException;
import app.maker.service.UserService;

/**
 * Servlet implementation class UserControleur
 */
public class UserControleur extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserControleur() {
		super();
		userService = new UserService();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
		user.setNom(request.getParameter("nom"));
		user.setPrenom(request.getParameter("prenom"));
		user.setDateArrivee(new Date());
		user.setAdresse(request.getParameter("adresse"));
		user.setEmail(request.getParameter("email"));
		user.setFonction(request.getParameter("fonction"));
		user.setSalaire(Float.parseFloat(request.getParameter("salaire")));
		user.setRole(Integer.parseInt(request.getParameter("role")));
		String login = user.getNom().substring(0, 1) + "@" + user.getPrenom();
		String paswd = user.getNom().substring(0, 1) + "@" + user.getPrenom();
		user.setLogin(login);
		user.setMotDePasse(paswd);
		user.setPhoto("maker/photos/employe.png");
		try {
			if (userService.add(user))
				response.sendRedirect(request.getContextPath()
						+ "/maker/admin/espace-utilisateurs.jsp");
			else {
				response.sendRedirect(request.getContextPath()
						+ "/maker/admin/erreur.jsp");
			}
		} catch (UserException e) {
			e.printStackTrace();
		}

	}

}
